#include "loginthread.h"
#include <QList>
#include <QFile>
#include <QTime>
#include <QByteArray>
#include "util/usersquota.h"

static QString temppath="/home/lou/Openstack/temp";
LoginThread::LoginThread(QObject *parent) : QThread(parent)
{
         qRegisterMetaType<LoginRes>("LoginRes");
}
LoginThread::~LoginThread()
{
         qDebug()<<"delete LoginThread";
}

void LoginThread::revPassage(QByteArray& passage,QTcpSocket* socket)
{
    m_passage=passage;
    m_pSocket=socket;
}
bool LoginThread::parsePassage(QByteArray& passage)
{
   QList<QByteArray>list = passage.split(',');
   if(list.size()==3)
   {
       login=list.at(1);
       passwd=list.at(2);
       return true;
   }
   return false;
}
LoginRes LoginThread::synData(QByteArray& result)
{
    UsersQuota userQuota;
    if(!userQuota.checkIdentity(login,passwd))
    {
        return L_IDENTITY_ERROR;
    }
    //创建获取用户当前信息的脚本
    QString currentTime=QTime::currentTime().toString();
    QString shPath=temppath+'/'+login+currentTime+".sh"; //启动脚本路径
    QString resPath=temppath+"/"+login+currentTime+".txt";//启动结果文本路径
    QFile fout(shPath);
    if(!fout.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        return L_FILE_OPEN_FAILED;
    }
    QTextStream stream(&fout);
    stream<<"#!/bin/sh\n";
    stream<<"export OS_PROJECT_DOMAIN_ID=default\n"
          <<"export OS_USER_DOMAIN_ID=default\n"
          <<"export OS_PROJECT_NAME="<<login<<"\n"
          <<"export OS_TENANT_NAME="<<login<<"\n"
          <<"export OS_USERNAME="<<login<<"\n"
          <<"export OS_PASSWORD="<<passwd<<"\n"
          <<"export OS_AUTH_URL=http://controller:5000/v3\n"
          <<"export OS_IDENTITY_API_VERSION=3\n";
    stream<<"nova list\n";
    fout.close();
    QString command;
    command.append("sh ").append(shPath).append(" >> ").append(resPath);
    int res = system(command.toStdString().c_str());
    fout.remove();
    if(res!=0)
    {
        return L_OPENSTACK_FAILD;
    }
    QFile fin(resPath);
    if(!fin.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        return L_FILE_OPEN_FAILED;
    }
    result= fin.readAll();
    fin.close();
    fin.remove();
    return L_OK;
}
void LoginThread::run()
{
    if(m_passage.isEmpty())
    {
        return;
    }
    if(!parsePassage(m_passage))
    {
        return;
    }
    QByteArray result;
    LoginRes res= synData(result);
    emit(replyLoginResult(m_pSocket,login,res,result));
}
